package com.shu.qq.data.interceptor

import android.util.Log
import cn.hutool.core.util.StrUtil
import com.shu.qq.common.Authentication
import com.shu.qq.data.QQService
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton

const val TAG = "shu-check"

@Singleton
class AuthenticationInterceptor @Inject constructor(private val authentication: Authentication) :
    Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val authorization = request.header(QQService.AUTHORIZATION_HEADER)
        Log.d(TAG, "intercept: 检查authorization请求类型：${authorization}")
        when {
            authorization.equals("login") -> {
                //删除标识头
                val newRequest =
                    request.newBuilder().removeHeader(QQService.AUTHORIZATION_HEADER).build()

                val response = chain.proceed(newRequest)

                if (response.isSuccessful) {  //请求成功
                    val token = response.header(QQService.AUTHORIZATION_HEADER, "") //获取token
                    if (token != null && token.isNotBlank()) {
                        authentication.token = token
                    }
                }
                return response
            }
            authorization.equals("register") -> {
                Log.d(TAG, "intercept: 注册处理")
                val newRequest =
                    request.newBuilder().removeHeader(QQService.AUTHORIZATION_HEADER).build()
                return chain.proceed(newRequest)
            }
            else -> {
                if (StrUtil.isNotBlank(authentication.token)) {
                    Log.d(TAG, "intercept: 请求添加token ${authentication.token}")
                    val newRequest = request.newBuilder()
                        .addHeader(QQService.AUTHORIZATION_HEADER, authentication.token).build()
                    return chain.proceed(newRequest)
                }
                Log.d(TAG, "intercept: 请求添加token ${authentication.token} , 获取本地的token为空")

                return chain.proceed(request)

            }
        }


    }
}